package cn.yann.demo.controller;

import cn.yann.demo.vertx.bus.TcpReceiveBusVerticle;
import cn.yann.demo.vertx.tcp.VertxTcpServeVerticle;
import io.vertx.core.Vertx;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

/**
 * @author Yann
 */
@Slf4j
@RestController
@RequestMapping("/api/vertx")
@RequiredArgsConstructor
public class VertxApiController {

    private final Vertx vertx;

    @PostMapping("/start-serve/{port}")
    public String startVertxServe(@PathVariable Integer port) {
        VertxTcpServeVerticle verticle = new VertxTcpServeVerticle(port);
        vertx.deployVerticle(verticle, res -> {
            if (res.succeeded()) {
                System.out.println("Deployment id is: " + res.result());
            } else {
                System.out.println("Deployment failed!");
            }
        });
        return "start:ok";
    }

    @PostMapping("/close-serve/{devId}")
    public String closeVertxServe(@PathVariable String devId) {
        vertx.undeploy(devId, res -> {
            if (res.succeeded()) {
                System.out.println("Undeployed ok");
            } else {
                System.out.println("Undeploy failed!");
            }
        });
        return "close:ok";
    }

    @PostMapping("/start-bus")
    public String startEventBus() {
        vertx.deployVerticle(new TcpReceiveBusVerticle(), res -> {
            if (res.succeeded()) {
                System.out.println("监听器bus: " + res.result());
            } else {
                System.out.println("Deployment failed!");
            }
        });
        return "bus:ok";
    }

    @GetMapping("/getDeploys")
    public String healthVertxServe() {
        Set<String> deploymentIDs = vertx.deploymentIDs();
        log.debug("部署的verticle: {}", deploymentIDs);
        return deploymentIDs.toString();
    }
}
